
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

using Swaf;
using Swaf.BizRule;
using Swaf.Scheduler;

namespace Syrinx
{
	public class KeepAliveBizRules : BaseBizRules
	{
		static Regex s_sid = new Regex(@"ASP\.NET_SessionId=([^;]+)");
		public void keepAspAppAlive(IApplication app, IRuleContext context, string url)
		{
			string result = null;
			try
			{
				HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
				myRequest.Method = "GET";
				string appKey = "KA_" + url.Replace(".", "");
				string aspSessionKey = app.appData.get(appKey) as string;
				if (aspSessionKey != null)
				{
					myRequest.Headers.Add(String.Format("Cookie: ASP.NET_SessionId={0}", aspSessionKey));
				}
				using(WebResponse myResponse = myRequest.GetResponse())
				using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
				{
					if (aspSessionKey == null)
					{
						Match m = s_sid.Match(myResponse.Headers.ToString());
						if(m.Success)
							app.appData.put(appKey, m.Groups[1].Value);
					}
					result = sr.ReadToEnd();
				}
			}
			catch (Exception e)
			{
				if (result != null)
					Swaf.Application.globalApp.Log.println(Swaf.Logging.LoggingLevels.High, "Exception on KeepAlive: {0}", e);
			}
		}
	}
}
